# -*- coding: utf-8 -*-

import hashlib
import urlparse
import time
import db_proxy

class biz:
    def __init__(self):
        self._db = db_proxy.db_proxy()

    def on_msg(self, msg):
        red_pkt_prefix = "https://weixin.spdbccc.com.cn/wxrp-page-redpacketsharepage/share"
        idx = -1
        if msg.MsgType == "link":
            idx = msg.Url.find(red_pkt_prefix)
        elif msg.MsgType == "text":
            idx = msg.Content.find(red_pkt_prefix)
        if idx == 0:
            # found!
            return self.on_red_pkt(msg)
        else:
            # unknown msg
            return self.on_other_msg(msg)

    def on_red_pkt(self, msg):
        msg_type = "red_pkt"
        if not self._db.user_exists(msg.FromUserName):
            self._db.add_user(msg.FromUserName)
        user_seq = self._db.get_user_seq(msg.FromUserName)

        # msg_id = hashlib.sha1(msg.Content).hexdigest()
        url_obj = urlparse.urlparse(msg.Url)
        if len(url_obj.query) is 0:
            return str(u"[无效红包]不要用假红包来欺骗感情哦!").encode("utf-8")
        qs = urlparse.parse_qs(url_obj.query)
        if "packetId" not in qs:
            return str(u"[找不到红包ID]不要用假红包来欺骗感情哦!").encode("utf-8")
        if len(qs["packetId"]) is 0:
            return str(u"[找不到红包ID]不要用假红包来欺骗感情哦!").encode("utf-8")
        pkt_id = qs["packetId"][0]
        if not self._db.pkt_exists(pkt_id):
            self._db.add_new_pkt(pkt_id, msg_type, user_seq,
                msg.CreateTime, msg.Url, msg.Description)
            self._db.add_user_pkt_history(user_seq, pkt_id)
            self._db.push_back_to_pkt_pool(pkt_id)
            red_pkt_urls = self.get_red_pkts(user_seq)
            if len(red_pkt_urls) == 0:
                return str(u"哎哟！没找到可用的红包，等加入的小伙伴多了就好了 ^_^").encode("utf-8")
            
            links = ""
            i = 1
            for u in red_pkt_urls:
                links = links + "["+str(i)+"] " + u + "\n"
                i = i + 1

            print links
            return links

        else:
            return str(u"坏蛋，用发过的红包欺骗我！T_T").encode("utf-8")

    def on_other_msg(self, msg):
        return str(u"你在说啥？").encode("utf-8")

    def get_red_pkts(self, who):
        urls = []
        available_pkts = []
        while len(urls) < 5:
            pkt_id = self._db.pop_front_from_pkt_pool()
            if pkt_id is None:
                break
            pkt = self._db.get_pkt(pkt_id)
            if pkt is None:
                continue
            now = int(time.time())
            if now > pkt["time"] and now - pkt["time"] > (24*60*60 - 60):
                continue

            if who == pkt["from"]:
                available_pkts.append(pkt_id)
                continue
            if self._db.has_shared(pkt_id, who):
                print str(who) + "has shared this packet from " + pkt["from"] + ". ignore! " + pkt_id
                available_pkts.append(pkt_id)
                continue
            if self._db.has_taken_today(who, pkt["from"]):
                print str(who) + "has taken one packet from " + pkt["from"] + " today. ignore! " + pkt_id
                available_pkts.append(pkt_id)
                continue
            urls.append(pkt["url"])
            self._db.take_from_one_today(who, pkt["from"])
            shared_cnt = self._db.update_pkt_shared(pkt_id, pkt["from"], who)
            if shared_cnt < 5:
                available_pkts.append(pkt_id)

        for m in available_pkts:
            self._db.push_front_to_pkt_pool(m)

        return urls
